package com.twetec.cms.adapter.pc.backend.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.twetec.cms.adapter.pc.backend.response.R;
import com.twetec.cms.common.constant.ConstantsEnum;
import com.twetec.cms.common.constant.RedisConst;
import com.twetec.cms.common.util.aes.AESUtils;
import com.twetec.cms.common.util.cache.RedisCache;
import com.twetec.cms.common.util.validate.ValidateUtil;
import com.twetec.cms.model.po.system.CmsRoleMenuPO;
import com.twetec.cms.model.po.system.CmsRolePO;
import com.twetec.cms.model.po.system.CmsUserRolePO;
import com.twetec.cms.model.po.user.UserPO;
import com.twetec.cms.model.vo.system.*;
import com.twetec.cms.model.vo.ucenter.UserListVO;
import com.twetec.cms.model.vo.ucenter.UserVO;
import com.twetec.cms.model.vo.website.CmsMenuPermissionListVO;
import com.twetec.cms.service.system.CmsMenuService;
import com.twetec.cms.service.system.CmsRoleMenuService;
import com.twetec.cms.service.system.CmsRoleService;
import com.twetec.cms.service.system.CmsUserRoleService;
import com.twetec.cms.service.ucenter.UserService;
import com.xxg.base.module.Operater;
import com.xxg.base.module.PageData;
import com.zgh.usercenter.module.User;
import com.zgh.usercenter.service.IUserCenterService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author wugaojian
 * @date 2022/2/9 11:01
 */
@Api(tags = "权限管理")
@RestController
@RequestMapping("/system/role")
public class CmsRoleController {

    @Autowired
    private CmsRoleService cmsRoleService;

    @Autowired
    private CmsRoleMenuService cmsRoleMenuService;

    @Autowired
    private UserService userService;

    @Autowired
    private CmsUserRoleService cmsUserRoleService;

    @Autowired
    private CmsMenuService cmsMenuService;

    @Autowired
    private RedisCache redisCache;

    @DubboReference(registry = {"union-platform"})
    private IUserCenterService iUserCenterService;


    @ApiOperation(value = "权限角色分页列表展示与搜索", notes = "权限角色分页列表展示与搜索")
    @GetMapping("/page-search-list")
    public R<CmsRolePageListVO> pageSearchList(@ApiParam(value = "角色名称", required = false, example = "管理员") @RequestParam(required = false) String roleName,
                                               @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                               @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) {

        if (page == null || !ValidateUtil.Number(page) || page <= 0) return R.failureRequestParam().msg("页码为空或格式不正确");
        if (limit == null || !ValidateUtil.Number(limit) || limit <= 0) return R.failureRequestParam().msg("页条目数为空或格式不正确");

        // 返回给前端的数据
        CmsRolePageListVO cmsRolePageListVO = new CmsRolePageListVO();
        // 预设返回值
        cmsRolePageListVO.setPage(page);
        cmsRolePageListVO.setLimit(limit);
        cmsRolePageListVO.setTotal(0);
        cmsRolePageListVO.setList(new ArrayList<>());

        // 条件构造器
        QueryWrapper<CmsRolePO> cmsRolePOQueryWrapper = new QueryWrapper<>();

        // 角色名称
        if (StringUtils.isNotEmpty(roleName)) {
            cmsRolePOQueryWrapper.like("NAME", roleName);
        }
        cmsRolePOQueryWrapper.orderByDesc("GMT_MODIFIED");

        // 开始分页查询
        Page<CmsRolePO> cmsRolePOPage = cmsRoleService.page(new Page<>(page, limit), cmsRolePOQueryWrapper);
        cmsRolePageListVO.setTotal((int) cmsRolePOPage.getTotal());
        cmsRolePageListVO.setPage((int) cmsRolePOPage.getCurrent());
        cmsRolePageListVO.setLimit((int) cmsRolePOPage.getSize());
        cmsRolePageListVO.setList(new ArrayList<>());

        List<CmsRolePO> records = cmsRolePOPage.getRecords();
        // 如果集合不为空
        if (!ValidateUtil.isNullOrEmpty(records)) {
            ArrayList<CmsRoleVO> cmsRoleVOList = new ArrayList<>();
            for (CmsRolePO cmsRolePO : records) {
                CmsRoleVO cmsRoleVO = new CmsRoleVO();
                BeanUtils.copyProperties(cmsRolePO, cmsRoleVO);

                // 操作人
                UserPO userPO = userService.getById(cmsRolePO.getModifierId());
                if (!ValidateUtil.isNullOrEmpty(userPO)) {
                    cmsRoleVO.setModifierName(userPO.getName());
                }
                cmsRoleVOList.add(cmsRoleVO);
            }
            cmsRolePageListVO.setList(cmsRoleVOList);
        }

        return R.success().data(cmsRolePageListVO);
    }

    @ApiOperation(value = "角色关联用户分页列表展示", notes = "角色关联用户分页列表展示")
    @GetMapping("/page-search-user-list-by-role-id")
    public R<CmsUserRolePageListVO> pageSearchUserListByRoleId(@ApiParam(value = "角色id", required = true, example = "123456789") @RequestParam(required = false) Long roleId,
                                          @ApiParam(value = "要访问的页码", required = true, example = "1") @RequestParam(required = false) Integer page,
                                          @ApiParam(value = "页面容量", required = true, example = "10") @RequestParam(required = false) Integer limit) throws Exception {

        if (roleId == null || !ValidateUtil.Number(roleId) || roleId <= 0) return R.failureRequestParam().msg("角色id不能为空");
        if (page == null || !ValidateUtil.Number(page) || page <= 0) return R.failureRequestParam().msg("页码为空或格式不正确");
        if (limit == null || !ValidateUtil.Number(limit) || limit <= 0) return R.failureRequestParam().msg("页条目数为空或格式不正确");

        CmsUserRolePageListVO cmsUserRolePageListVO = new CmsUserRolePageListVO();
        // 预设返回值
        cmsUserRolePageListVO.setPage(page);
        cmsUserRolePageListVO.setLimit(limit);
        cmsUserRolePageListVO.setTotal(0);
        cmsUserRolePageListVO.setList(new ArrayList<>());

        // 条件构造器
        QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();

        // 根据roleId从关系表中可以得到一个拥有相同角色的userRole集合
        cmsUserRolePOQueryWrapper.eq("ROLE_ID", roleId);
        Page<CmsUserRolePO> cmsUserRolePOPage = cmsUserRoleService.page(new Page<>(page, limit), cmsUserRolePOQueryWrapper);
        cmsUserRolePageListVO.setTotal((int) cmsUserRolePOPage.getTotal());
        cmsUserRolePageListVO.setPage((int) cmsUserRolePOPage.getCurrent());
        cmsUserRolePageListVO.setLimit((int) cmsUserRolePOPage.getSize());
        cmsUserRolePageListVO.setList(new ArrayList<>());

        List<CmsUserRolePO> records = cmsUserRolePOPage.getRecords();
        if (!ValidateUtil.isNullOrEmpty(records)) {
            ArrayList<CmsUserRoleVO> cmsUserRoleVOList = new ArrayList<>();
            // 一条记录就代表关联表中的一个
            for (CmsUserRolePO userRolePO : records) {
                QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
                // 通过userId去用户表中查
                userPOQueryWrapper.eq("ID", userRolePO.getUserId());
                // 得到一个用户对象
                UserPO userPO = userService.getOne(userPOQueryWrapper, false);
                // 开始复制属性到VO
                CmsUserRoleVO cmsUserRoleVO = new CmsUserRoleVO();
                BeanUtils.copyProperties(userPO, cmsUserRoleVO);
                String credentialNumber = AESUtils.decrypt(userPO.getCredentialNumber());
                String tel = AESUtils.decrypt(userPO.getTelephone());
                cmsUserRoleVO.setCredentialNumber(credentialNumber);
                cmsUserRoleVO.setTelephone(tel);
                cmsUserRoleVO.setId(userRolePO.getId());
                cmsUserRoleVOList.add(cmsUserRoleVO);
            }
            cmsUserRolePageListVO.setList(cmsUserRoleVOList);
        }
        return R.success().data(cmsUserRolePageListVO);
    }

    @Transactional
    @ApiOperation(value = "新增角色", notes = "新增角色")
    @PostMapping("/create")
    public R create(@ApiParam(value = "角色名称", required = true, example = "管理员") @RequestParam(required = true) String name,
                    @ApiParam(value = "菜单权限ids", required = true, example = "123456789,123965487") @RequestParam(required = true) String ids,
                    @RequestAttribute("userId") Long userId) {
        if (name == null || StringUtils.isEmpty(name)) {
            return R.failureRequestParam().msg("角色名称不能为空");
        }
//        if (StringUtils.isEmpty(ids)) return R.failureRequestParam().msg("菜单权限ids不能为空");

        // 保存角色
        CmsRolePO cmsRolePO = new CmsRolePO();
        cmsRolePO.setName(name);
        cmsRolePO.setCreatorId(userId);
        cmsRolePO.setModifierId(userId);

        boolean roleResult = cmsRoleService.save(cmsRolePO);
        if (!roleResult) {
            return R.failure().msg("创建角色失败");
        }

        // 如果没有赋予权限，则创建角色成功即返回
        if (null == ids || StringUtils.isEmpty(ids)) {
            return R.success().msg("成功");
        }

        // 如果只有一个菜单
        if (!ids.contains(",")) {
            CmsRoleMenuPO cmsRoleMenuPO = new CmsRoleMenuPO();
            cmsRoleMenuPO.setRoleId(cmsRolePO.getId());
            cmsRoleMenuPO.setMenuId(Long.valueOf(ids));
            boolean roleMenuResult = cmsRoleMenuService.save(cmsRoleMenuPO);
            if (!roleMenuResult) {
                return R.failure().msg("授权菜单失败");
            }

        } else {
            // 如果不止一个菜单
            // 将菜单权限ids分割
            String[] split = ids.split(",");

            // 保存角色与菜单的关联关系
            ArrayList<CmsRoleMenuPO> CmsRoleMenuList = new ArrayList<>();
            for (String s : split) {
                CmsRoleMenuPO cmsRoleMenuPO = new CmsRoleMenuPO();
                cmsRoleMenuPO.setRoleId(cmsRolePO.getId());
                cmsRoleMenuPO.setMenuId(Long.valueOf(s));
                CmsRoleMenuList.add(cmsRoleMenuPO);
            }
            boolean roleMenuResult = cmsRoleMenuService.saveBatch(CmsRoleMenuList);
            if (!roleMenuResult) {
                return R.failure().msg("授权菜单失败");
            }
        }
        return R.success().msg("成功");
    }

    @Transactional
    @ApiOperation(value = "根据id获取角色", notes = "根据id获取角色")
    @GetMapping("/get-by-id")
    public R<CmsRoleItemVO> getById(@ApiParam(value = "角色id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id) {
        if (id == null || StringUtils.isEmpty(String.valueOf(id))) return R.failureRequestParam().msg("角色id不能为空");

        CmsRoleItemVO cmsRoleItemVO = new CmsRoleItemVO();
        CmsRolePO cmsRolePO = cmsRoleService.getById(id);

        // 如果没有查询到数据
        if (null == cmsRolePO) {
            return R.failure().data(cmsRoleItemVO);
        }

        // 查询到则查询角色对应的菜单权限
        QueryWrapper<CmsRoleMenuPO> cmsRoleMenuPOQueryWrapper = new QueryWrapper<>();
        cmsRoleMenuPOQueryWrapper.lambda().eq(CmsRoleMenuPO::getRoleId, id);
        List<CmsRoleMenuPO> roleMenuList = cmsRoleMenuService.list(cmsRoleMenuPOQueryWrapper);
        if (null != roleMenuList && !roleMenuList.isEmpty()) {
            // 将其拼接为字符串
            StringBuffer idStrBuffer = new StringBuffer();
            roleMenuList.forEach(roleMenuPO -> {
                idStrBuffer.append(roleMenuPO.getMenuId()).append(",");
            });
            int indexOf = idStrBuffer.lastIndexOf(",");
            String idString = idStrBuffer.substring(0, indexOf);
            cmsRoleItemVO.setMenuIds(idString);
        }
        cmsRoleItemVO.setId(cmsRolePO.getId());
        cmsRoleItemVO.setName(cmsRolePO.getName());

        return R.success().data(cmsRoleItemVO);
    }

    @Transactional
    @ApiOperation(value = "根据id编辑角色", notes = "根据id编辑角色")
    @PutMapping("/update-by-id")
    public R updateById(@ApiParam(value = "角色id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id,
                        @ApiParam(value = "角色名称", required = false, example = "角色名称1") @RequestParam(required = false) String name,
                        @ApiParam(value = "菜单权限ids", required = true, example = "123456789,123965487") @RequestParam(required = true) String ids,
                        @RequestAttribute("userId") Long userId) {
        if (name == null || StringUtils.isEmpty(name)) return R.failureRequestParam().msg("角色名称不能为空");

        CmsRolePO cmsRolePO = new CmsRolePO();
        cmsRolePO.setId(id);
        cmsRolePO.setName(name);
        cmsRolePO.setModifierId(userId);
        boolean updateRole = cmsRoleService.updateById(cmsRolePO);

        if (!updateRole) return R.failure().msg("创建角色失败");

        // 清除原本赋予的权限
        QueryWrapper<CmsRoleMenuPO> cmsRoleMenuPOQueryWrapper = new QueryWrapper<>();
        cmsRoleMenuPOQueryWrapper.lambda().eq(CmsRoleMenuPO::getRoleId, id);
        boolean removeRoleMenu = cmsRoleMenuService.remove(cmsRoleMenuPOQueryWrapper);
        if (!removeRoleMenu) return R.failure().msg("失败");

        // 如果权限列表为空
        if (StringUtils.isEmpty(ids)) return R.success().msg("成功");

        // 如果权限列表不为空
        // 如果只有一个菜单
        if (!ids.contains(",")) {
            CmsRoleMenuPO cmsRoleMenuPO = new CmsRoleMenuPO();
            cmsRoleMenuPO.setRoleId(cmsRolePO.getId());
            cmsRoleMenuPO.setMenuId(Long.valueOf(ids));
            boolean roleMenuResult = cmsRoleMenuService.save(cmsRoleMenuPO);
            if (!roleMenuResult) return R.failure().msg("授权菜单失败");
        } else {
            // 如果不止一个菜单
            // 将菜单权限ids分割
            String[] split = ids.split(",");

            // 保存角色与菜单的关联关系
            ArrayList<CmsRoleMenuPO> CmsRoleMenuList = new ArrayList<>();
            for (String s : split) {
                CmsRoleMenuPO cmsRoleMenuPO = new CmsRoleMenuPO();
                cmsRoleMenuPO.setRoleId(cmsRolePO.getId());
                cmsRoleMenuPO.setMenuId(Long.valueOf(s));
                CmsRoleMenuList.add(cmsRoleMenuPO);
            }
            boolean roleMenuResult = cmsRoleMenuService.saveBatch(CmsRoleMenuList);

            // 从redis中将所有用户的站点权限删除
            boolean deletePermission = cmsRoleMenuService.deleteUserPermission();

            if (!roleMenuResult) return R.failure().msg("授权菜单失败");
        }
        return R.success().msg("成功");
    }

    @ApiOperation(value = "菜单权限树", notes = "菜单权限树")
    @GetMapping("/permission-tree")
    public R<CmsMenuPermissionListVO> permissionTree() {
        CmsMenuPermissionListVO cmsMenuPermissionListVO = cmsMenuService.permissionTree();
        return R.success().data(cmsMenuPermissionListVO);
    }


    @ApiOperation(value = "查询工会用户列表", notes = "查询工会用户列表")
    @GetMapping("/user-list")
    public R<UserListVO> userList(@ApiParam(value = "电话", required = false, example = "123456789123") @RequestParam(required = false) String phone,
                                  @ApiParam(value = "证件号码", required = false, example = "56156424X") @RequestParam(required = false) String IDCard,
                                  @ApiParam(value = "证件类型", required = false, example = "") @RequestParam(required = false) String cardType,
                                  @RequestAttribute("userId") Long userId) throws ParseException {
        // 查询工会用户列表
        String idcardType = "";
        // 身份证
        if (cardType != null) {
            if (cardType.equals(ConstantsEnum.CredentialType.ID_CARD.getValue())) {
                idcardType = "1";
            } else if (cardType.equals(ConstantsEnum.CredentialType.GO_HOME_CARD.getValue())) {
                idcardType = "2";
            } else if (cardType.equals(ConstantsEnum.CredentialType.TAIWAN_COMPATRIOTS_CARD.getValue())) {
                // 台胞证
                idcardType = "3";
            } else if (cardType.equals(ConstantsEnum.CredentialType.PASSPORT_CARD.getValue())) {
                // 护照
                idcardType = "4";
            }
        }
        // 查询条件
        Map<String, Object> map = new HashMap<>();
        if (!StringUtils.isBlank(IDCard)) {
            map.put("idcardCode", IDCard);
        }

        if (!StringUtils.isBlank(idcardType)) {
            map.put("idcardType", idcardType);
        }

        if (!StringUtils.isBlank(phone)) {
            map.put("mobile", phone);
        }

        if (StringUtils.isBlank(idcardType) && StringUtils.isBlank(IDCard) && StringUtils.isBlank(phone)) {
            return R.success();
        }

        // 操作者数据
        Operater operater = redisCache.getObj(RedisConst.REDISKEY_OPERATER_INFO + userId, Operater.class);
        // 获取数据
        List<User> users = iUserCenterService.listUser(map, operater, new PageData());

        UserListVO userListVO = new UserListVO();
        if (users == null) {
            return R.success().data(userListVO);
        }

        ArrayList<UserVO> userVOS = new ArrayList<>();
        for (User user : users) {
            UserVO userVO = p_convertData(user);
            userVOS.add(userVO);
        }
        userListVO.setList(userVOS);

        return R.success().data(userListVO);
    }


    @ApiOperation(value = "关联用户与角色", notes = "关联用户与角色")
    @GetMapping("/relate-user-and-role")
    public R relateUserAndRole(@ApiParam(value = "工会会员ids", required = false, example = "14655645451654,546451542545") @RequestParam(required = false) String  unionMemberIds,
                               @ApiParam(value = "角色id", required = false, example = "123456789123") @RequestParam(required = false) Long roleId,
                               @RequestAttribute("userId") Long userId) throws Exception {
        if (null == unionMemberIds || StringUtils.isEmpty(unionMemberIds)) return R.failureRequestParam().msg("工会会员id不能为空");
        if (null == roleId || StringUtils.isEmpty(String.valueOf(roleId))) return R.failureRequestParam().msg("角色id不能为空");

        ArrayList<Long> userIdList = new ArrayList<>();

        // 只选中了一个会员
        if (!unionMemberIds.contains(",")) {
            QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
            userPOQueryWrapper.eq("UNION_MEMBER_ID", unionMemberIds);
            UserPO userPO = userService.getOne(userPOQueryWrapper);
            if (null != userPO) {
                userIdList.add(userPO.getId());
            } else {
                // 在本系统中没有则
                // 查询工会用户信息
                // 构建查询条件
                Map<String, Object> params = new HashMap<>();
                if (unionMemberIds != null) {
                    params.put("userIds", unionMemberIds);
                }
                // 操作者数据
                Operater operater = redisCache.getObj(RedisConst.REDISKEY_OPERATER_INFO + userId, Operater.class);
                // 分页数据
                PageData pageData = new PageData();
                // 获取数据
                List<User> users = iUserCenterService.listUser(params, operater, pageData);
                if (null == users) {
                    return R.failure();
                }
                List<UserVO> userList = new ArrayList<>();
                // 整理数据格式
                for (User user : users) {
                    UserVO userVO = p_convertData(user);
                    userList.add(userVO);

                    // 先将工会用户信息保存到数据库
                    UserPO userUnionPO = new UserPO();
                    // 加密码电话与身份证号码
                    String credentialNumber = AESUtils.encrypt(userVO.getCredentialNumber());
                    String tel = AESUtils.encrypt(userVO.getTelephone());
                    BeanUtils.copyProperties(userVO, userUnionPO);
                    userUnionPO.setCredentialNumber(credentialNumber);
                    userUnionPO.setTelephone(tel);

                    boolean save = userService.save(userUnionPO);
                    // 将用户id保存到集合中
                    userIdList.add(userUnionPO.getId());
                }
            }
        } else {
            // 不止一个会员
            // 查询会员id对应的用户
            String[] split = unionMemberIds.split(",");
            List<String> unionMemberIdList = Arrays.asList(split);
            QueryWrapper<UserPO> userPOQueryWrapper = new QueryWrapper<>();
            userPOQueryWrapper.in("UNION_MEMBER_ID", unionMemberIdList);
            List<UserPO> userList = userService.list(userPOQueryWrapper);
            // 如果一个都没有查到
            if (null == userList || userList.isEmpty()) {
                //  查询工会用户信息
                Map<String, Object> params = new HashMap<>();
                if (unionMemberIds != null) {
                    params.put("userIds", unionMemberIds);
                }
                // 操作者数据
                Operater operater = redisCache.getObj(RedisConst.REDISKEY_OPERATER_INFO + userId, Operater.class);
                // 分页数据
                PageData pageData = new PageData();
                // 获取数据
                List<User> users = iUserCenterService.listUser(params, operater, pageData);
                if (null == users) {
                    return R.failure();
                }
                List<UserPO> userPOList = new ArrayList<>();
                // 整理数据格式
                for (User user : users) {
                    UserVO userVO = p_convertData(user);
                    UserPO userPO = new UserPO();

                    // 加密码电话与身份证号码
                    String credentialNumber = AESUtils.encrypt(userVO.getCredentialNumber());
                    String tel = AESUtils.encrypt(userVO.getTelephone());
                    BeanUtils.copyProperties(userVO, userPO);
                    userPO.setCredentialNumber(credentialNumber);
                    userPO.setTelephone(tel);
                    userPOList.add(userPO);
                }

                boolean save = userService.saveBatch(userPOList);
                // 将用户id保存到集合中
                for (UserPO userPO : userPOList) {
                    userIdList.add(userPO.getId());
                }
            }

            // 要绑定角色的会员在数据库有一部分,有一部分没有
            if (userList.size() < split.length) {

                // 查到部分，则将查询到的会员id放入userIdList
                for (UserPO userPO : userList) {
                    userIdList.add(userPO.getId());
                }
                // 将已经有的去除，将剩下的没有的会员存到数据库
                ArrayList<String> stringArrayList = new ArrayList<>();
                for (UserPO userPO : userList) {
                    stringArrayList.add(userPO.getUnionMemberId());
                }
                StringBuffer unionMemberId = new StringBuffer();
                for (String s : unionMemberIdList) {
                    if (stringArrayList.contains(s)) continue;
                    unionMemberId.append(",");
                    unionMemberId.append(s);
                }
                // 没在数据库中的工会会员的会员id
                String unionMemberIdStr = unionMemberId.toString().substring(unionMemberId.toString().indexOf(",") + 1);

                // 将不在数据库的会员同步到数据库中
                Map<String, Object> params = new HashMap<>();
                if (!unionMemberIdStr.isEmpty()) {
                    params.put("userIds", unionMemberIdStr);
                }
                // 操作者数据
                Operater operater = redisCache.getObj(RedisConst.REDISKEY_OPERATER_INFO + userId, Operater.class);
                // 分页数据
                PageData pageData = new PageData();
                // 获取数据
                List<User> users = iUserCenterService.listUser(params, operater, pageData);
                if (null == users) {
                    return R.failure();
                }
                List<UserPO> userPOList = new ArrayList<>();
                // 整理数据格式
                for (User user : users) {
                    UserVO userVO = p_convertData(user);
                    UserPO userPO = new UserPO();
                    //加密码电话与身份证号码
                    String credentialNumber = AESUtils.encrypt(userVO.getCredentialNumber());
                    String tel = AESUtils.encrypt(userVO.getTelephone());
                    BeanUtils.copyProperties(userVO, userPO);
                    userPO.setCredentialNumber(credentialNumber);
                    userPO.setTelephone(tel);
                    userPOList.add(userPO);
                }

                // 将没有的用户保存到数据库
                boolean save = userService.saveBatch(userPOList);
                // 将用户id保存到集合中
                for (UserPO userPO : userPOList) {
                    userIdList.add(userPO.getId());
                }
            } else {
                // 获得了全部的工会会员id
                for (UserPO userPO : userList) {
                    userIdList.add(userPO.getId());
                }
            }
        }
        // 查询此角色下所有的用户
        QueryWrapper<CmsUserRolePO> cmsUserRolePOQueryWrapper = new QueryWrapper<>();
        cmsUserRolePOQueryWrapper.lambda().eq(CmsUserRolePO::getRoleId, roleId);
        List<CmsUserRolePO> list = cmsUserRoleService.list(cmsUserRolePOQueryWrapper);
        // 若角色与用户已经绑定过就不再绑定
        for (CmsUserRolePO userRolePO : list) {
            userIdList.remove(userRolePO.getUserId());
        }
        // 如果全部都已经绑定了，直接返回成功
        if (userIdList.isEmpty()) {
            return R.success();
        }

        // 保存用户与角色关系
        ArrayList<CmsUserRolePO> cmsUserRolePOS = new ArrayList<>();
        for (Long aLong : userIdList) {
            CmsUserRolePO userRolePO = new CmsUserRolePO();
            userRolePO.setRoleId(roleId);
            userRolePO.setUserId(aLong);
            cmsUserRolePOS.add(userRolePO);
        }

        boolean saveBatch = cmsUserRoleService.saveBatch(cmsUserRolePOS);
        if (!saveBatch) {
            return R.failure();
        }
        // 删除
        boolean deletePermission = cmsRoleMenuService.deleteUserPermission();

        if (!deletePermission) {
            return R.failure();
        }

        return R.success();
    }

    @ApiOperation(value = "根据角色和权限关联表id移除用户", notes = "根据角色和权限关联表id移除用户")
    @DeleteMapping("/delete-user-role-by-id")
    public R deleteUserRoleById(@ApiParam(value = "关联表id", required = true, example = "1440511185542696962") @RequestParam(required = false) Long id) {

        if (null == id || !ValidateUtil.Number(id) || id <= 0) {
            return R.failureRequestParam().msg("id不能为空");
        }
        CmsUserRolePO userRolePO = cmsUserRoleService.getById(id);
        boolean result = cmsUserRoleService.removeById(id);
        if (!result) {
            return R.failure().msg("移除失败或关联不存在！");
        }

        // 删除用户的站点权限缓存
        String key = RedisConst.REDISKEY_PERMISSION_MENU + userRolePO.getUserId();
        boolean delete = redisCache.delete(key);
        if (!delete) {
            return R.failure().msg("删除缓存失败！");
        }

        return R.success().msg("移除成功！");
    }

    /**
     * 把工会会员数据整理成本系统中的用户数据
     */
    private UserVO p_convertData(User user) throws ParseException {

        Long unionMemberId = user.getId();
        String fullName = user.getFullName();
        String avatar = "";
        String idcardType = user.getIdcardType();
        String idcardCode = user.getIdcardCode();
        String mobile = user.getMobile();
        String status = ConstantsEnum.Enable.ON.getValue();
        String birthday = user.getBirthday();
        String sex = user.getSex();
        String companyName = user.getCompanyName();
        String labourUnionName = user.getLabourUnionName();

        // 时间整理
        SimpleDateFormat formatter = new SimpleDateFormat( "yyyyMMdd");
        Date newBirthday = null;
        if (birthday != null) {
            newBirthday = formatter.parse(birthday);
        }

        if (sex != null) {
            // 男性
            if (sex.equals("1")) {
                sex = ConstantsEnum.Gender.MALE.getValue();
            } else if (sex.equals("2")) {
                // 女性
                sex = ConstantsEnum.Gender.FEMALE.getValue();
            } else {
                // 其他
                sex = ConstantsEnum.Gender.MALE.getValue();
            }
        }

        // 身份证
        if (idcardType != null) {
            if (idcardType.equals("1")) {
                idcardType = ConstantsEnum.CredentialType.ID_CARD.getValue();
            } else if (idcardType.equals("2")) {
                // 回乡证
                idcardType = ConstantsEnum.CredentialType.GO_HOME_CARD.getValue();
            } else if (idcardType.equals("3")) {
                // 台胞证
                idcardType = ConstantsEnum.CredentialType.TAIWAN_COMPATRIOTS_CARD.getValue();
            } else if (idcardType.equals("4")) {
                // 护照
                idcardType = ConstantsEnum.CredentialType.PASSPORT_CARD.getValue();
            }
        }

        // 整理数据
        UserVO userVO = new UserVO();
        userVO.setId(unionMemberId);
        userVO.setUnionMemberId(String.valueOf(unionMemberId));
        userVO.setName(fullName);
        userVO.setAvatar(avatar);
        userVO.setCredentialType(idcardType);
        userVO.setCredentialNumber(idcardCode);
        userVO.setTelephone(mobile);
        userVO.setBirthDate(newBirthday);
        userVO.setGender(sex);
        userVO.setUnit(companyName);
        userVO.setUnions(labourUnionName);

        return userVO;
    }

}
